from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from typing import List

from app.db.database import get_db
from app.services.spot_service import SpotService
from app.schemas.spot_schema import SpotCreate, SpotUpdate, SpotOut
from app.schemas.common_schema import R

router = APIRouter(prefix="/spots", tags=["景点"])


@router.post("/", response_model=R[SpotOut])
def create_spot(obj: SpotCreate, db: Session = Depends(get_db)):
    code, msg, data = SpotService.create_spot(db, obj)
    if data:
        return R(code=code, message=msg, data=data)
    raise HTTPException(status_code=code, detail=msg)


@router.get("/", response_model=R[List[SpotOut]])
def list_spots(
    city: str = Query(None),
    keyword: str = Query(None),
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db),
):
    code, msg, data = SpotService.list_spots(db, city=city, keyword=keyword, skip=skip, limit=limit)
    return R(code=code, message=msg, data=data)


@router.get("/{spot_id}", response_model=R[SpotOut])
def get_spot(spot_id: int, db: Session = Depends(get_db)):
    code, msg, data = SpotService.get_spot(db, spot_id)
    if data:
        return R(code=code, message=msg, data=data)
    raise HTTPException(status_code=code, detail=msg)


@router.patch("/{spot_id}", response_model=R[SpotOut])
def update_spot(spot_id: int, obj: SpotUpdate, db: Session = Depends(get_db)):
    code, msg, data = SpotService.update_spot(db, spot_id, obj)
    if data:
        return R(code=code, message=msg, data=data)
    raise HTTPException(status_code=code, detail=msg)


@router.delete("/{spot_id}", response_model=R)
def delete_spot(spot_id: int, db: Session = Depends(get_db)):
    code, msg = SpotService.delete_spot(db, spot_id)
    if code == 200:
        return R(code=code, message=msg)
    raise HTTPException(status_code=code, detail=msg)